Kotlin有4種不同的Visibility Modifiers
private, protected, internal 和 public
Functions, properties and classes, objects 和 interfaces可直接宣告在package中宣告
// file name: example.kt
package foo
fun baz() {}
class Bar {}
// file name: example.kt
package foo
private fun foo() {} // 只在example.kt可存取
public var bar: Int = 5 // 對外皆可存取
private set // 只在example.kt可存取
internal val baz = 6 // 只在相同module可存取
宣告在類別中的成員變數
open class Outer {
private val a = 1
protected open val b = 2
internal val c = 3
val d = 4 // 預設public
protected class Nested {
public val e: Int = 5
}
}
class Subclass : Outer() {
// a 是不可見的
// b, c, d, e 可以存取
override val b = 5 // 'b' is protected
}
class Unrelated(o: Outer) {
// o.a, o.b 不能存取
// o.c and o.d 相同module可以存取
}